package com.hnichr.ping.signature.impl;

import com.hnichr.ping.signature.SignatureProvider;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

@Component
public class HmacSHA1SignatureProvider implements SignatureProvider {

    private static final String METHOD = "HMAC-SHA1";


    private static final String HMAC_SHA1 = "HmacSHA1";

    @Override
    public String getMethod() {
        return METHOD;
    }

    @Override
    public String getSignature(Map<String, String> param,String appSecret) {

        TreeMap<String,String> treeMap = new TreeMap<>(param);
        List<String> valuesList = new ArrayList<>();
        for(Map.Entry<String,String> entry:treeMap.entrySet()){
            valuesList.add(entry.getValue());
        }
        String values = String.join("&",valuesList);
        try{
            String encodedValues = URLEncoder.encode(values,"UTF-8");
            Mac mac = Mac.getInstance(HMAC_SHA1);
            SecretKeySpec spec = new SecretKeySpec(appSecret.getBytes(), HMAC_SHA1);
            mac.init(spec);
            byte[] byteHMAC = mac.doFinal(encodedValues.getBytes());
            Base64 base64 = new Base64();
            return base64.encodeAsString(byteHMAC);
        }
        catch (Exception e){
            return null;
        }
    }
}
